<?php 
class AdSearch extends Object
{
	public $UserId;
	public $UserEmail;
	public $AdTypeId;
	public $AdTypeTitle;
	public $AdCatId;
	public $AdCatTitle;
	public $AdBrandId;
	public $AdBrandTitle;
	
	public $DateCreated;
	public $DateLastSent;
	
	public $Title;
	public $AndString;
	public $UrlString;
	public $Active;
	
	public function AdSearch($values = '')
	{ 
		self::setDataTable('am_ad_search');
		if(is_array($values))
		{ self::setValues($values); }
	}
	
	public function getUserId() { return intval($this->UserId); }
	public function getAdTypeId() { return intval($this->AdTypeId); }
	public function getAdCatId() { return intval($this->AdCatId); }
	public function getBrandId() { return intval($this->BrandId); }
	
	public function setUserId($val) { $this->UserId=intval($val); }
	public function setAdTypeId($val) { $this->AdTypeId=intval($val); }
	public function setAdCatId($val) { $this->AdCatId=intval($val); }
	public function setBrandId($val) { $this->BrandId=intval($val); }

	
	public function getDateCreated()
	{ 
		if($format != '')
		{ return self::formatDateTime($this->DateCreated, $format); }
		else
		{ return $this->DateCreated; }
	}
	public function getDateLastSent()
	{ 
		if($format != '')
		{ return self::formatDateTime($this->DateLastSent, $format); }
		else
		{ return $this->DateLastSent; }
	}
	
	public function loadUrlString()
	{
		if(!($this->UrlString != ''))
		{
			$this->UrlString = '';
			if(is_array($_GET))
			{
				foreach(array_keys($_GET) as $param)
				{
					switch($param)
					{
						case 'adcat':
						case 'adtype':
						case 'adbrand':
						break;
						
						case 'brands':
							if(is_array($_GET[$param]))
							{
								foreach($_GET[$param] as $p)
								{ $this->UrlString .= $param.'[]='.$p.'&'; }
							}
						break;
						
						default:
							if($_GET[$param] != '')
							{ $this->UrlString .= $param.'='.$_GET[$param].'&'; }
						break;
					}
				}
			}
		}
	}
	
	public function getLink()
	{
		$out = '/';
		if(self::getAdCatId() > 0)
		{ $out .= 'adcat/'.self::getAdCatId().'/'; }
		else if(self::getAdTypeId() > 0)
		{ $out .= 'adtype/'.self::getAdTypeId().'/'; }
		if(self::getAdBrandId() > 0)
		{ $out .= 'adbrand/'.self::getAdBrandId().'/'; }
		
		if($out == '/')
		{ $out = '/list/ad/'; }
		
		if(self::getUrlString() != '')
		{ $out .= '?'.self::getUrlString(); }
		else
		{
			if(self::getAndString() != '')
			{ $out .= '?search='.self::getId(); }
		}
		return $out;
	}
	
	function insert()
	{
		global $user;
		if((self::getUserId() > 0) && (self::getTitle() != '') && ($user->getId() == self::getUserId()))
		{
			$insert = '`UserId`';
			$values = self::getUserId();
			
			$insert .= ', `AdTypeId`';
			$values .= ', '.self::getAdTypeId();
			
			$insert .= ', `AdCatId`';
			$values .= ', '.self::getAdCatId();
			
			$insert .= ', `AdBrandId`';
			$values .= ', '.self::getAdBrandId();
			
			$insert .= ', `Title`';
			$values .= ', "'.self::formatText(self::getTitle(), 100).'"';
				
			$insert .= ', `AndString`';
			$values .= ", '".self::getAndString()."'";
			
			$insert .= ', `UrlString`';
			$values .= ", '".self::getUrlString()."'";
			
			$insert .= ', `DateCreated`';
			$values .= ', NOW()';
			
			$insert .= ', `DateLastSent`';
			$values .= ', NOW()';
			
			$insert .= ', `Active`';
			$values .= ', '.self::getActive();
			
			$sql  = 'INSERT INTO '.DB_PERFIX.self::getDataTable().' ('.$insert.') '; 
			$sql .= 'VALUES ('.$values.');';
			$result = mysql_query($sql);
			//echo $sql;
			$sql = 'SELECT id FROM '.DB_PERFIX.self::getDataTable().' WHERE `userId`='.self::getUserId().' ORDER BY id DESC LIMIT 1;';
			$result = mysql_query($sql);
			if(mysql_num_rows($result) > 0)
			{
				while($row = mysql_fetch_array($result))
				{ self::setId($row['id']); }
			}
		}
	}
	
	function update()
	{
		if((self::getId() > 0) && (self::getDataChanged()))
		{
			$sql  = 'UPDATE '.DB_PERFIX.self::getDataTable().' SET ';
			$sql .= '`AdTypeId`='.self::getAdTypeId().', ';
			$sql .= '`AdCatId`='.self::getAdCatId().', ';
			$sql .= '`AdBrandId`='.self::getAdBrandId().', ';
			$sql .= '`Title`="'.self::formatText(self::getTitle(), 100).'", ';
			$sql .= '`DateLastSent`="'.self::getDateLastSent().'", ';
			$sql .= '`Active`='.self::getActive().' ';
			$sql .= ' WHERE Id='.self::getId().' LIMIT 1;';
			//echo $sql;
			mysql_query($sql);
		}
	}
	
	function sendNewAds()
	{
		global $adc;
		
		if((self::getActive() > 0) && (self::getUserEmail() != '') && (self::getAndString() != ''))
		{
			$out = self::getTitle().' Checking for active Ads<br />';
			
			$adc->setCurrentAdTypeId(0);
			$adc->setCurrentAdCatId(0);
			$adc->setCurrentAdBrandId(0);
			$adc->setCurrentAdId(0);
			if(self::getAdTypeId() > 0)
			{ $adc->setCurrentAdTypeId(self::getAdTypeId()); }
			
			if(self::getAdCatId() > 0)
			{ $adc->setCurrentAdCatId(self::getAdCatId()); }
			
			if(self::getAdBrandId() > 0)
			{ $adc->setCurrentAdBrandId(self::getAdBrandId()); }
			
			$adc->Search['AND'] = self::getAndString().' AND dateCreated > "'.self::getDateLastSent().'" ';

			$adc->loadAds();
			
			$newAds = $adc->Ads;
			
			$table = '';
			
			$table = '';
			$rows  = '';
			
			if(count($newAds) > 0)
			{
				global $txt;
				global $katana;
				global $mailCSS;
				
				$date = new DateTime(date('y-m-d h:i:s'));
				$date->add(new DateInterval('P1D'));
				self::setDateLastSent($date->format('Y-m-d 00:00:00'));
				self::setDataChanged(true);
				self::update();
				
				$table = '';
				$rows  = '';
				$body  = '';
				
				$count = 0;
				
				foreach($newAds as $ad)
				{
					$rows .= 		'<tr>';
					/*
					$rows .= 			'<td valign="top" style="width:200px; '.$mailCSS['fontstyle'].$mailCSS['borderBottom'].' ">';
					$rows .= 				'<a href="'.SITE_URL.'ad/'.$ad->getId().'">'.$txt->truncate($ad->getTitle(), 30, '', '', '').'</a>&nbsp;&nbsp;';
					$rows .= 			'</td>';
					*/
					$rows .= 			'<td valign="top" style=" line-height:22px; '.$mailCSS['fontstyle'].$mailCSS['borderBottom'].'">';
					$rows .= 				'<a href="'.SITE_URL.'ad/'.$ad->getId().'/">'.$txt->truncate($ad->getSummary(), 200, '', '', '').'</a>&nbsp;&nbsp;';
					$rows .= 			'</td>';
					//$rows .= 			'<td valign="top" style="'.$mailCSS['fontstyle'].$mailCSS['borderBottom'].'">'.$ad->getSummary().'&nbsp;&nbsp;</td>';
					$rows .= 			'<td valign="top" style="line-height:22px; '.$mailCSS['fontstyle'].$mailCSS['borderBottom'].' width:120px;" align="right">';
					$rows .= 				$ad->getLocationCity();
					$rows .= 			'</td>';
					$rows .= 			'<td valign="top" style="line-height:22px; '.$mailCSS['fontstyle'].$mailCSS['borderBottom'].' width:80px;" align="right">&nbsp;';
					if(($ad->getUsePrice() > 0) && ($ad->getPriceGlobalTxt(0) != '0'))
					{
						switch($adc->getViewObject())
						{
							default:
								if($ad->getUsePrice() > 0)
								{ 
									if($ad->getPriceDisplay() > 0) 
									{ $rows .= $ad->getPriceGlobalTxt(0).' NOK'; }
									else
									{ $rows .= ucfirst($txt->getWord('price_at_request')); }
								}
							break;
						}
					}
					$rows .= 			'</td>';
					$rows .= 			'<td>&nbsp;</td>';
					$rows .= 		'</tr>';
					$count++;
					//$rows .= 		'<tr><td colspan="4" style="'.$mailCSS['borderBottom'].'">&nbsp;</td></tr>';
				}
				
				if($rows != '')
				{
					$table .= '<table align="left" style="margin-top:10px; width:660px; '.$mailCSS['fontstyle'].'" cellpadding="1" cellspacing="0" border="0">';
					$table .= '    <thead>';
					$table .= 		'<tr>';
					//$table .= 			'<th style="'.$mailCSS['borderBottom'].' text-align:left;">'.ucfirst($txt->getWord('title')).'</th>';
					$table .= 			'<th style="'.$mailCSS['borderBottom'].' text-align:left;">'.ucfirst($txt->getWord('ad')).'</th>';
					$table .= 			'<th style="'.$mailCSS['borderBottom'].' text-align:right;" align="right">'.ucfirst($txt->getWord('location')).'</th>';
					$table .= 			'<th style="'.$mailCSS['borderBottom'].' text-align:right;" align="right">'.ucfirst($txt->getWord('price')).'</th>';
					$table .= 			'<th>&nbsp;</th>';
					$table .= 		'</tr>';
					$table .= '    </thead>';
					$table .= '    <tbody>';
					$table .= $rows;
					$table .= '    </tbody>';
					$table .= '</table><br clear="all" />';
				}
				
				if($table != '')
				{
					$body .= '<body style="'.$mailCSS['fontstyle'].'">';
					$body .= '<h3 style="'.$mailCSS['fontstyleHeading'].'">'.ucfirst($txt->getWord('hello')).'</h3>';
					$body .= '<p style="'.$mailCSS['fontstyle'].'">';
					$body .= $katana->getTitle().' har f&aring;tt inn f&oslash;lgende annonser som passer til ditt lagrede s&oslash;k: <b>'.self::getTitle().'</b>';
					$body .= '</p>';
					$body .= $table;
					$body .= '<br /><br />';
					$body .= '<p style="'.$mailCSS['fontstyle'].'">';
					$body .= 	'S&oslash;ket kan deaktiveres ved &aring; logge inn p&aring; ';
					$body .= 	'<a href="'.SITE_URL.'c/11/"><b>MinProfil</b></a>, velge <b>'.ucfirst($txt->getWord('my_searches')).'</b> og klikke p&aring; <b>Deaktiver sending</b><br />';
					$body .= '</p><p style="'.$mailCSS['borderTop'].'">&nbsp;</p>';
					$body .= $katana->getCompanyMailFooter($fontstyle);
					$body .= '<a href="'.SITE_URL.'"><img width="232" height="40" border="0" alt="'.$katana->getTitle().' Logo" src="'.SITE_URL.'files/images/LogoAnLast.png" /></a>';
					$body .= '</body>';

					$mail = new Email($katana);
					$mail->setTo(self::getUserEmail());
					$mail->setFrom($katana->getCompanyEmail());
					$mail->setFromName($katana->getTitle().' Autofunn');
					$mail->setSubject($katana->getTitle().' Autofunn');
					$mail->setBody($body);
					$mail->send();
					
					$out .= '<br />Found'.$count.' matching for userId:'.self::getUserId().' with e-mail:'.self::getUserEmail();
					$out .= '<br />Emails sent<br /><hr />';
				}
			}
		}
		return $out; 
	}
}
?>